﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Scrutor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace My.Core.DynamicProxy
{
    /// <summary>
    /// 动态代理类
    /// </summary>
    public class DynamicProxyClass
    {
        static DynamicProxyClass()
        {
        }

		/// <summary>
		/// 启动
		/// </summary>
		/// <param name="serviceCollection"></param>
		/// <param name="assemblies">要扫描的程序集</param>
		/// <param name="RegistrationStrategy">注册模式</param>
		public static void Start(IServiceCollection serviceCollection, IEnumerable<Assembly> assemblies, RegistrationStrategy RegistrationStrategy)
        {
            // 服务自动注册
            ScanningDiInterface(serviceCollection, assemblies, RegistrationStrategy);
        }

        /// <summary>
        /// 服务自动注册
        /// </summary>
        private static void ScanningDiInterface(IServiceCollection serviceCollection, IEnumerable<Assembly> assemblies, RegistrationStrategy RegistrationStrategy)
        {
            serviceCollection.Scan(w =>
            {
                w.FromAssemblies(assemblies)
                    //接口注册Scoped
                    .AddClasses(classes => classes.AssignableTo(typeof(IScopedAutoInject)))
						.UsingRegistrationStrategy(RegistrationStrategy)
						.AsImplementedInterfaces()
                        .WithScopedLifetime()
                    //接口注册Singleton
                    .AddClasses(classes => classes.AssignableTo(typeof(ISingletonAutoInject)))
						.UsingRegistrationStrategy(RegistrationStrategy)
						.AsImplementedInterfaces()
                        .WithSingletonLifetime()
                    //接口注册Transient
                    .AddClasses(classes => classes.AssignableTo(typeof(ITransientAutoInject)))
						.UsingRegistrationStrategy(RegistrationStrategy)
						.AsImplementedInterfaces()
                        .WithTransientLifetime()
                    //具体类注册Scoped
                    .AddClasses(classes => classes.AssignableTo(typeof(ISelfScopedAutoInject)))
					    .UsingRegistrationStrategy(RegistrationStrategy)
						.AsSelf()
                        .WithScopedLifetime()
                    //具体类注册Singleton
                    .AddClasses(classes => classes.AssignableTo(typeof(ISelfSingletonAutoInject)))
						.UsingRegistrationStrategy(RegistrationStrategy)
						.AsSelf()
                        .WithSingletonLifetime()
                    //具体类注册Transient
                    .AddClasses(classes => classes.AssignableTo(typeof(ISelfTransientAutoInject)))
						.UsingRegistrationStrategy(RegistrationStrategy)
						.AsSelf()
                        .WithTransientLifetime();
            });
        }
    }
}
